package com.machinecontroller.utils;

import com.easivend.evprotocol.EVprotocol;
import com.google.gson.Gson;
import com.machinecontroller.constant.McConfig;
import com.machinecontroller.model.EVModel;

/**
 * 设备工具类，用于控制开门，获取状态等
 * Created by zhangxuehui on 2017/12/17.
 */
public class EVControlerUtil {

    /**
     * 打开门
     *
     * @param addr
     * @param box
     * @return
     */
    public static boolean openDoor(int addr, int box) {
        int portId = registEv();
        if (portId == 0) {
            portId = registEv();
        }
        if (portId < 0) {
            closeEv();
            return false;
        }
        String json = EVprotocol.EVBentoOpen(portId, addr, box);
        EVModel mParentModel = parseObject(json, EVModel.class);
        EVModel.EV_json mModel = mParentModel.getEV_json();
        closeEv();
        if (mModel.getResult() == 0) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 转换类型
     *
     * @param json
     * @param evModelClass
     * @return
     */
    private static EVModel parseObject(String json, Class<EVModel> evModelClass) {
        Gson gson = new Gson();
        return gson.fromJson(json, evModelClass);
    }

    /**
     * 释放串口号
     *
     * @return
     */
    private static void closeEv() {
        EVprotocol.EVPortRelease(McConfig.MC_PORT_NUM);
    }

    /**
     * 注册串口号
     *
     * @return
     */
    private static int registEv() {
        String json = EVprotocol.EVPortRegister(McConfig.MC_PORT_NUM);
        EVModel model = parseObject(json, EVModel.class);
        EVModel.EV_json mModel = model.getEV_json();
        int port_id = mModel.getPort_id();
        return port_id;
    }


    /**
     * 返回未关门的格子号
     *
     * @return
     */
    public static String getDoorState() {
        int portId = registEv();
        if (portId == 0) {
            portId = registEv();
        }
        if (portId < 0) {
            closeEv();
            return "";
        }
        String errDoorNo = "";
        String json = EVprotocol.EVBentoCheck(portId, McConfig.MC_BOX_NUN);
        EVModel mParentModel = parseObject(json, EVModel.class);
        EVModel.EV_json mModel = mParentModel.getEV_json();
        if (mModel.getIs_success() == 1) {
            StringBuffer sb = new StringBuffer();
            for (EVModel.EV_json.SumModel m : mModel.getSum()) {
                if (m.getState().equals("0")) {
                    sb.append(m.getNo() + ",");
                }
            }
            errDoorNo = sb.toString();
        }
        EVprotocol.EVPortRelease(McConfig.MC_PORT_NUM);
        return errDoorNo;
    }

}
